package com.xiyu.service.model.material.order;

import com.xiyu.service.model.material.stock.MaterialStockDetailTable;
import org.babyfish.jimmer.sql.JSqlClient;
import org.babyfish.jimmer.sql.TransientResolver;
import org.babyfish.jimmer.sql.ast.Expression;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Component
public class MaterialTransferDetailStockResolver implements TransientResolver<Long, Long> {
    private final JSqlClient sqlClient;

    public MaterialTransferDetailStockResolver(JSqlClient sqlClient) {
        this.sqlClient = sqlClient;
    }

    @Override
    public Map<Long, Long> resolve(Collection<Long> ids) {
        List<Long> stockDetailId = sqlClient
                .createQuery(MaterialStockDetailTable.$)
                .where(Expression.tuple(
                        MaterialStockDetailTable.$.warehouseId(),
                        MaterialStockDetailTable.$.materialId(),
                        MaterialStockDetailTable.$.batchNo(),
                        MaterialStockDetailTable.$.productionDate(),
                        MaterialStockDetailTable.$.expireDate()
                ).in(sqlClient
                        .createSubQuery(MaterialTransferDetailTable.$)
                        .where(MaterialTransferDetailTable.$.id().in(ids))
                        .select(
                                MaterialTransferDetailTable.$.transfer().outWarehouseId(),
                                MaterialTransferDetailTable.$.materialId(),
                                MaterialTransferDetailTable.$.batchNo(),
                                MaterialTransferDetailTable.$.productionDate(),
                                MaterialTransferDetailTable.$.expireDate()
                        ))
                )
                .select(MaterialStockDetailTable.$.id())
                .execute();
        return IntStream.range(0, Math.min(ids.size(), stockDetailId.size()))
                .boxed()
                .collect(Collectors.toMap(
                        i -> (Long) ids.toArray()[i], // 键为 Collection<Long> ids 的元素
                        stockDetailId::get // 值为 List<Long> stockDetailId 的对应索引位置的元素
                ));
    }

}
